
"""
Register a connector function for obtaining a connection to a gadfly SQL database
before executing the dispatcher.

(primarily for testing).
"""

import chatLogic
from whiff.middleware import misc
from whiff import resolver
from whiff import whiffenv

class gadflyTestConnection(misc.utility):
    def __init__(self,
                 Dispatcher,
                 TempDir="/tmp",
                 AutoCreateTables=False,
                 DbPrefix="Testgf",
                 DatabaseName="testchat",
                 DirectoryName = "testdatabase",
                 ):
        self.Dispatcher = Dispatcher
        self.TempDir = TempDir
        self.AutoCreateTables = AutoCreateTables
        self.DbPrefix = DbPrefix
        self.DatabaseName = DatabaseName
        self.DirectoryName = DirectoryName
    def __call__(self, env, start_response):
        # materialize parameters
        TempDir = self.param_value(self.TempDir, env).strip()
        AutoCreateTables = self.param_json(self.AutoCreateTables, env)
        DbPrefix = self.param_value(self.DbPrefix, env).strip()
        DatabaseName = self.param_value(self.DatabaseName, env).strip()
        DirectoryName = self.param_value(self.DirectoryName, env).strip()
        # define the connector function
        def getConnection():
            path = TempDir+"/"+DirectoryName
            connection = chatLogic.test_gadfly_connection(DbPrefix, DatabaseName, path)
            # note: this will not create the database: just the tables if they are not there and the database exists.
            if AutoCreateTables:
                connection.autoCreateTables()
            return connection
        env = chatLogic.registerConnector(getConnection, env)
        # deliver the dispatch page
        return self.deliver_page(self.Dispatcher, env, start_response)

__middleware__ = gadflyTestConnection

